import {v4 as uuid4} from "uuid"
import * as  redis from "redis"

const client = redis.createClient({
    host: "127.0.0.1",
    port: "6379"
})

export default class Jwt {
    private readonly timeLimit: number;

    /**
     * @param {number} timeLimit 有效期限
     */
    constructor(timeLimit = 60 * 5) {
        this.timeLimit = timeLimit
    }

    /**
     * @description 生成token
     * @returns {string} token
     */
    generateToken(userid) {
        const token = uuid4()
        client.set(token, userid)
        client.expire(token, this.timeLimit)
        return token
    }

    /**
     * @description 检验token
     * @returns {Promise<boolean>}
     */
    verifyToken(token) {
        if (!token) {
            throw Error('token is required!')
        }
        return new Promise((resolve) => {
            client.get(token, (err, userid) => {
                if (err) resolve(false)
                resolve(userid)
            })
        })
    }
}
